package com.tollge.business.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class TencentCloudAPIDemo {

    public static String sign(String s) {
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
        try {
            mac.init(secretKeySpec);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] hash = mac.doFinal(s.getBytes(StandardCharsets.UTF_8));
        return DatatypeConverter.printBase64Binary(hash);
    }

    static String reqDomain = "cns.api.qcloud.com/v2/index.php?";
    static String secretId = "AKIDEF2YoK80wb2ZrtPkFaMwPilJtDH5FWVE";
    static String secretKey = "iPq1xmBMGziANJWD5gbW9WdngJflfjX8";

    public static String getStringToSign(SortedMap<String, Object> params) {
        StringBuilder s2s = new StringBuilder("GET" +  reqDomain);
        // 签名时要求对参数进行字典排序，此处用TreeMap保证顺序
        for (String k : params.keySet()) {
            s2s.append(k).append("=").append(params.get(k).toString()).append("&");
        }
        return s2s.substring(0, s2s.length() - 1);
    }

    public static String getUrl(SortedMap<String, Object> params) {
        // 实际请求的url中对参数顺序没有要求
        String paramsUrl = params.entrySet().stream().map(k -> k.getKey() + "=" + encode(k.getValue().toString())).collect(Collectors.joining("&"));
        return "https://" + reqDomain + paramsUrl;
    }

    public static String encode(String string) {
        try {
            return URLEncoder.encode(string, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String generateQueryUrl(String domain, String subDomain) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("SecretId", secretId);
        params.put("Nonce", new Random().nextInt(Integer.MAX_VALUE));
        params.put("Timestamp", System.currentTimeMillis() / 1000);

        params.put("Version", "2018-08-08");

        params.put("Action", "RecordList");
        params.put("subDomain", subDomain);
        params.put("domain", domain);

        params.put("Signature", sign(getStringToSign(params)));
        return getUrl(params);
    }

    public static String generateUpdateUrl(Integer recordId, String domain, String subDomain, String ip) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("SecretId", secretId);
        params.put("Nonce", new Random().nextInt(Integer.MAX_VALUE));
        params.put("Timestamp", System.currentTimeMillis() / 1000);

        params.put("Version", "2018-08-08");
        params.put("recordType", "A");
        params.put("recordLine", "默认");

        params.put("Action", "RecordModify");
        params.put("recordId", recordId);
        params.put("subDomain", subDomain);
        params.put("domain", domain);
        params.put("value", ip);

        params.put("Signature", sign(getStringToSign(params)));
        return getUrl(params);
    }

    public static void main(String[] args) throws Exception {

        System.out.println(generateQueryUrl("tollge.cn", "*"));
    }
}
